package notify

import (
	"bytes"
	"context"
	Conf "cronjob_work/common/config"
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"log"
	"time"
)

type Dingtalk struct {
	Dingtalks map[string]string
	Content   map[string]interface{}
}

var DingtalkChan chan *Dingtalk
var DingtalkUrl string

func init() {
	ctx := context.Background()
	noticeConfig := Conf.Newconfig()
	DingtalkUrl = noticeConfig.GetString(ctx, "dingtalk.url")
	poolSize := noticeConfig.GetInt(ctx, "dingtalk.pool")

	//创建通道
	DingtalkChan = make(chan *Dingtalk, poolSize)

	go func() {
		for {
			select {
			case m, ok := <-DingtalkChan:
				if !ok {
					return
				}
				if err := m.SendDingtalk(ctx); err != nil {
					g.Log().Error(ctx, "SendDingtalk:", err.Error())

				}
			}
		}
	}()

}

func SendDingtalkToChan(dingtalks map[string]string, content map[string]interface{}) bool {
	dingTalk := &Dingtalk{
		Dingtalks: dingtalks,
		Content:   content,
	}

	select {
	case DingtalkChan <- dingTalk:
		return true
	case <-time.After(time.Second * 3):
		return false
	}
}

func (s *Dingtalk) SendDingtalk(ctx context.Context) error {
	for _, v := range s.Dingtalks {
		body, err := json.Marshal(s.Content)
		if err != nil {
			log.Println(err)
			return err
		}

		url := fmt.Sprintf(DingtalkUrl, v)
		header := make(map[string]string, 0)
		header["Content-Type"] = "application/json"
		header["charset"] = "utf-8"
		_, resErr := g.Client().SetHeaderMap(header).Post(ctx, url, bytes.NewBuffer(body))
		if resErr != nil {
			log.Println(resErr)
			return resErr
		}
		return nil
	}
	return nil
}
